package com.leon.notepad.content;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.leon.notepad.R;
import com.leon.notepad.audio.AudioPlayManager;
import com.leon.notepad.audio.AudioRecordManager;
import com.leon.notepad.audio.IAudioPlayListener;
import com.leon.notepad.audio.IAudioRecordListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.leon.notepad.content.adapter.FullyGridLayoutManager;
import com.leon.notepad.content.adapter.GridImageAdapter;
import com.leon.notepad.content.bean.NotepadBean;
import com.leon.notepad.content.view.RecordAudioButton;
import com.leon.notepad.content.view.RecordVoicePopWindow;
import com.leon.notepad.content.view.VoiceImageView;

import org.litepal.LitePal;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

public class AddNotepadActivity extends BaseActivity {

    @BindView(R.id.edit_msg)
    EditText editMsg;
    @BindView(R.id.iv_voice)
    VoiceImageView ivVoice;
    @BindView(R.id.iv_del_voice)
    ImageView ivDelVoice;
    @BindView(R.id.ll_del_voice)
    LinearLayout llDelVoice;
    @BindView(R.id.rl_voice)
    RelativeLayout rlVoice;
    @BindView(R.id.btnVoice)
    RecordAudioButton mBtnVoice;
    @BindView(R.id.bg)
    LinearLayout bg;
    @BindView(R.id.bt_add)
    TextView btAdd;
    @BindView(R.id.recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.edit_title)
    EditText editTitle;

    private GridImageAdapter adapter;
    private List<LocalMedia> selectList = new ArrayList<>();
    private static final String AUDIO_DIR_NAME = "audio_cache";
    private static final int MAX_VOICE_TIME = 20;//声音最大时间
    private RecordVoicePopWindow mRecordVoicePopWindow;//提示
    private File mAudioDir;
    private List<File> mListData = new ArrayList<>();

    private String type;
    private NotepadBean mBean = new NotepadBean();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_notepad);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        if ("modify".equals(type)) {//修改点进来的，需要先赋值
            mBean = (NotepadBean) intent.getSerializableExtra("item");
            editMsg.setText(mBean.getContent());
            editTitle.setText(mBean.getTitle());
            btAdd.setText("修改");
            if (mBean.getImage() != null && !mBean.getImage().equals("")) {
                List<LocalMedia> list = new Gson().fromJson(mBean.getImage(), new TypeToken<List<LocalMedia>>() {
                }.getType());
                Log.e("1231", "123");
                selectList.addAll(list);
            }
            if (mBean.getSound() != null && !mBean.getSound().equals("")) {
                rlVoice.setVisibility(View.VISIBLE);
                mBtnVoice.setVisibility(View.GONE);
                File file = new File(mBean.getSound());
                mListData.add(file);
            }

        }
        mAudioDir = new File(getExternalCacheDir(), AUDIO_DIR_NAME);
        if (!mAudioDir.exists()) {//判断文件夹是否存在，不存在则创建
            mAudioDir.mkdirs();
        }
        initAudioManager();
        mBtnVoice.setOnVoiceButtonCallBack(new RecordAudioButton.OnVoiceButtonCallBack() {
            @Override
            public void onStartRecord() {//开始录音
                AudioRecordManager.getInstance(AddNotepadActivity.this).startRecord();
            }

            @Override
            public void onStopRecord() {//停止录音
                AudioRecordManager.getInstance(AddNotepadActivity.this).stopRecord();
            }

            @Override
            public void onWillCancelRecord() {//将要取消录音（参与微信手指上滑）
                AudioRecordManager.getInstance(AddNotepadActivity.this).willCancelRecord();

            }

            @Override
            public void onContinueRecord() {//继续录音（参与微信手指上滑后加下滑回到原位）
                AudioRecordManager.getInstance(AddNotepadActivity.this).continueRecord();

            }
        });
        initWidget();
    }

    /**
     * 初始化选择图片控件
     */
    private void initWidget() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(9);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(AddNotepadActivity.this).externalPicturePreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(AddNotepadActivity.this).externalPictureVideo(media.getPath());
                            break;
                        case 3:
                            // 预览音频
                            PictureSelector.create(AddNotepadActivity.this).externalPictureAudio(media.getPath());
                            break;
                    }
                }
            }
        });
    }

    @OnClick({R.id.iv_voice, R.id.ll_del_voice})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_voice:
                startPlayRecord();
                break;
            case R.id.ll_del_voice:
                rlVoice.setVisibility(View.GONE);
                mBtnVoice.setVisibility(View.VISIBLE);
                mListData.clear();
                break;
        }
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {

        @Override
        public void onAddPicClick() {
            //获取读写的权限
            RxPermissions rxPermission = new RxPermissions(AddNotepadActivity.this);
            rxPermission.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean aBoolean) throws Exception {
                            if (aBoolean) {
                                //相册
                                PictureSelector.create(AddNotepadActivity.this)
                                        .openGallery(PictureMimeType.ofImage())
                                        .maxSelectNum(9)
                                        .minSelectNum(1)
                                        .selectionMode(PictureConfig.MULTIPLE)
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                            } else {
                                Toast.makeText(AddNotepadActivity.this, "请授权，否则无法使用", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
    };

    /**
     * activity回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images;
        // 图片选择结果回调
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    images = PictureSelector.obtainMultipleResult(data);
                    Log.e("123", "!!" + images.size());
                    selectList.addAll(images);
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    /**
     * 播放录制的音频
     */
    public void startPlayRecord() {
        File item = mListData.get(0);
        Uri audioUri = Uri.fromFile(item);
        Log.d("P_startPlayRecord", audioUri.toString());
        AudioPlayManager.getInstance().startPlay(this, audioUri, new IAudioPlayListener() {
            @Override
            public void onStart(Uri var1) {//开播（一般是开始语音消息动画）
                ivVoice.startPlay();
            }

            @Override
            public void onStop(Uri var1) { //停播（一般是停止语音消息动画）
                ivVoice.stopPlay();
            }

            @Override
            public void onComplete(Uri var1) {//播完（一般是停止语音消息动画）
                ivVoice.stopPlay();
            }
        });
    }

    /**
     * 初始化音频播放管理对象
     */
    private void initAudioManager() {
        AudioRecordManager.getInstance(this).setAudioSavePath(mAudioDir.getAbsolutePath());
        AudioRecordManager.getInstance(this).setMaxVoiceDuration(MAX_VOICE_TIME);
        AudioRecordManager.getInstance(this).setAudioRecordListener(new IAudioRecordListener() {
            @Override
            public void initTipView() {//初始化提示视图
                if (mRecordVoicePopWindow == null) {
                    mRecordVoicePopWindow = new RecordVoicePopWindow(AddNotepadActivity.this);
                }
                mRecordVoicePopWindow.showAsDropDown(bg);
            }

            @Override
            public void setTimeoutTipView(int counter) {//设置倒计时提示视图
                if (mRecordVoicePopWindow != null) {
                    mRecordVoicePopWindow.showTimeOutTipView(counter);
                }
            }

            @Override
            public void setRecordingTipView() {//设置正在录制提示视图
                if (mRecordVoicePopWindow != null) {
                    mRecordVoicePopWindow.showRecordingTipView();
                }
            }

            @Override
            public void setAudioShortTipView() {//设置语音长度太短提示视图
                if (mRecordVoicePopWindow != null) {
                    mRecordVoicePopWindow.showRecordTooShortTipView();
                }
            }

            @Override
            public void setCancelTipView() {//设置取消提示视图
                if (mRecordVoicePopWindow != null) {
                    mRecordVoicePopWindow.showCancelTipView();
                }
            }

            @Override
            public void destroyTipView() {//销毁提示视图
                if (mRecordVoicePopWindow != null) {
                    mRecordVoicePopWindow.dismiss();
                }
            }

            @Override
            public void onStartRecord() {

            }

            /**
             * 录制结束
             *
             * @param audioPath 语音文件路径
             * @param duration  语音文件时长
             */
            @Override
            public void onFinish(Uri audioPath, int duration) {
                File file = new File(audioPath.getPath());
                if (file.exists()) {
                    Toast.makeText(AddNotepadActivity.this, "录制成功", Toast.LENGTH_SHORT).show();
                    mListData.clear();
                    mListData.add(file);
                    mBtnVoice.setVisibility(View.GONE);
                    rlVoice.setVisibility(View.VISIBLE);
                }
            }

            /**
             * 分贝改变
             *
             * @param db 分贝
             */
            @Override
            public void onAudioDBChanged(int db) {
                if (mRecordVoicePopWindow != null) {
                    mRecordVoicePopWindow.updateCurrentVolume(db);
                }
            }
        });
    }

    @OnClick(R.id.bt_add)
    public void onClick() {
        String title = editTitle.getText().toString();
        String content = editMsg.getText().toString();
        if (title.equals("")) {
            Toast.makeText(AddNotepadActivity.this, "请输入标题", Toast.LENGTH_SHORT).show();
            return;
        }else if (content.equals("")) {
            Toast.makeText(AddNotepadActivity.this, "请输入内容", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("modify".equals(type)) {
            ContentValues values = new ContentValues();
            values.put("content", content);
            values.put("title", title);
            int i = 0;
            if (selectList.size() > 0) {
                String image = new Gson().toJson(selectList);
                values.put("image", image);
                i = 1;
            } else {
                values.put("image", "");
            }
            if (mListData.size() > 0) {
                i = 1;
                values.put("sound", mListData.get(0).getPath());
            } else {
                values.put("sound", "");
            }
            values.put("type", i);
            LitePal.update(NotepadBean.class, values, mBean.getId());
        } else {
            NotepadBean bean = new NotepadBean();
            bean.setContent(content);
            bean.setTitle(title);
            bean.setTime(System.currentTimeMillis());
            int type = 0;
            if (selectList.size() > 0) {
                String image = new Gson().toJson(selectList);
                bean.setImage(image);
                type = 1;
            }
            if (mListData.size() > 0) {
                bean.setSound(mListData.get(0).getPath());
                type = 1;
            }
            bean.setType(type);
            bean.save();
        }
        setResult(RESULT_OK);
        finish();
    }
}